import React, { Component } from "react";
import { Form, Input, Modal, Checkbox, Row, Col } from "antd";
import { openNotificationWithIcon } from "utils/comm";
import yujing from "../../assets/images/yujing.png";
import Tags from "../../pages/messagemanage/notificationtemplatemanagement/components/Tags";
import styles from "./MessageEditModal.less";

const { TextArea } = Input;

const formItemLayout = {
  labelCol: { span: 24 },
  wrapperCol: { span: 24 },
};

const formItemLayout1 = {
  labelCol: { span: 10 },
  wrapperCol: { span: 14 },
};

@Form.create()
class MessageEditModal extends Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.inputRef = React.createRef();
    this.textareaRef = React.createRef();
    this.state = {
      templateParam: [], // 通知模板参数
      // record: {},
    };
  }

  componentDidMount() {
    this.initStaticData();
  }

  initStaticData = () => {
    const { dispatch, paramType } = this.props;
    // 获取模板参数
    dispatch({
      type: "FlowChart/getTemplateParameter",
      payload: { type: paramType },
    }).then(({ errCode, datas }) => {
      if (errCode === 0) {
        this.setState({
          templateParam: datas,
        });
      }
    });
  };

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, title, content, onCancel, onOk } = this.props;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      values.title = values.title && values.title.trim();
      const { title: newTitle, content: newContent } = values;

      onOk(newTitle || title, newContent || content);
      onCancel();
    });
  };

  tagClick = (tag) => {
    const { form } = this.props;
    window.addEventListener("mousedown", (e) => {
      if (e.target.id === "param") e.preventDefault();
      if (e.target.id !== "param") this.focusPos = e.target.id;
    });
    const input = document.getElementById("title");
    const InputIndex = input.selectionStart;
    const textArea = document.getElementById("content");
    const textIndex = textArea.selectionStart;
    const inputValue = input.value || "";
    const textValue = textArea.value || "";
    if (this.focusPos === "title") {
      input.value = `${inputValue.slice(0, InputIndex)}${tag}${inputValue.slice(
        InputIndex,
        inputValue.length - 1,
      )}`;
      form.setFieldsValue({
        title: input.value,
      });
      form.validateFields(["title"]);
    }
    if (this.focusPos === "content") {
      textArea.value = `${textValue.slice(0, textIndex)}${tag}${textValue.slice(
        textIndex,
        textValue.length - 1,
      )}`;
      form.setFieldsValue({
        content: textArea.value,
      });
      form.validateFields(["content"]);
    }
  };

  render() {
    const { templateParam } = this.state;
    const { form, onCancel, title, content, visible, record } = this.props;

    let notieTitle = "";
    let noticeContent = "";
    if (record) {
      notieTitle = record.title;
      noticeContent = record.content;
    }
    // const { title: notieTitle = "", content: noticeContent = "" } = record;

    const { getFieldDecorator } = form;

    return (
      <Modal
        title="流程预警消息设置"
        visible={visible}
        onOk={this.handleOk}
        onCancel={onCancel}
        width="582px"
        centered
        destroyOnClose
        className={styles.root}
        hideRequiredMark
        labelAlign="left"
      >
        <Row>
          <Col span={12} style={{ display: "flex", alignItems: "center" }}>
            <img src={yujing} alt="" />
          </Col>
          <Col span={12}>
            <Form>
              <div className={styles.marginBo}>
                <div className={styles.label}>模板参数：</div>
                <Form.Item
                  label=""
                  {...formItemLayout}
                  style={{ marginBottom: 16 }}
                  help="选择模版参数的时候，注意光标位置，支持标题和内容。"
                >
                  {getFieldDecorator("param")(
                    <Tags data={templateParam} tagClick={this.tagClick} />,
                  )}
                </Form.Item>
              </div>

              <div className={styles.marginBo}>
                <div className={styles.label}>消息标题：</div>
                <Form.Item label="" {...formItemLayout}>
                  {getFieldDecorator("title", {
                    initialValue: title || notieTitle || "",
                    rules: [
                      { max: 20, message: "请不要超过20个字符" },
                      { required: true, message: "请输入消息标题" },
                    ],
                  })(
                    <Input
                      id="title"
                      placeholder="请输入消息标题"
                      onFocus={() => {
                        this.focusPos = "title";
                      }}
                    />,
                  )}
                </Form.Item>
              </div>

              <div className={styles.marginBo}>
                <div className={styles.label}>消息内容：</div>
                <Form.Item label="" {...formItemLayout}>
                  {getFieldDecorator("content", {
                    initialValue: content || noticeContent || "",
                    rules: [
                      { max: 100, message: "请不要超过100个字符" },
                      { required: true, message: "请输入消息内容" },
                    ],
                  })(
                    <TextArea
                      id="content"
                      placeholder="消息内容"
                      rows={4}
                      onFocus={() => {
                        this.focusPos = "content";
                      }}
                    />,
                  )}
                </Form.Item>
              </div>

              <Form.Item label="消息接收人：" {...formItemLayout1}>
                {getFieldDecorator("status", {
                  // initialValue: record.status || false,
                  // rules: [{ required: true, message: "" }],
                })(
                  <Checkbox checked disabled>
                    发起人
                  </Checkbox>,
                )}
              </Form.Item>
            </Form>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default MessageEditModal;
